import { Upload } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import React from 'react';
import type { UploadChangeParam, UploadFile } from 'antd/lib/upload/interface';

class Avatar extends React.Component<{
  imageUrl?: string;
  action?: string;
  uploadCompletion: (imageUrl?: string) => void;
}> {
  state = {
    loading: false,
    imageUrl: this.props.imageUrl || '',
  };

  handleChange = (info: UploadChangeParam<UploadFile<any>>) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      const { data, code, message } = info.file.response;

      if (code === 0) {
        this.setState({
          loading: false,
          imageUrl: data.url,
        });
        if (this.props.uploadCompletion) {
          this.props.uploadCompletion(data.url);
        }
      } else {
        message.error(message);
        this.setState({
          loading: false,
        });
      }
    }
  };

  render() {
    const { loading, imageUrl } = this.state;
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <Upload
        name="file"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={this.props.action}
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    );
  }
}

export default Avatar;
